package cn.jee.jsp;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.hsqldb.types.Charset;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@WebServlet("/down")
public class DownServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String fileName=req.getParameter("file");

    String realPath=req.getServletContext().getRealPath("/uploads");
    Path srcPath= Paths.get(realPath,fileName);
    System.out.println(srcPath+" "+ Files.exists(srcPath));
    resp.setContentType(Files.probeContentType(srcPath));
    //弹出对话框 inline
//    resp.setHeader("Content-Disposition","attachment;");
    resp.setHeader("Content-Disposition","attachment; filename="+toCn(fileName));
    Files.copy(srcPath,resp.getOutputStream());
  }
  static String toCn(String fileName){
    return new String(fileName.getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1);
  }

}
